package com.feihong.yw189.http;


import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.LogUtils;
import com.feihong.yw189.activity.MyActivityManager;
import com.feihong.yw189.activity.denglu.DengLuActivity;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.message.FroceLogOutMessage;
import com.feihong.yw189.utils.ComPareUtils;
import com.feihong.yw189.utils.MyLoginUtils;
import com.feihong.yw189.utils.PreferenceTools;
import com.feihong.yw189.utils.ThreadPoolManager;
import com.feihong.yw189.utils.UserLoginInfo;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.KeyValue;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

/**
 * @author wangziheng
 * @name txgw_app
 * @class name：com.feihong.txgw.http
 * @class describe:   网络请求二次简易封装
 * @time 2017/9/5 16:03
 * @change
 * @chang time
 * @class describe
 */
public class HttpManage {
    public static final String TAG = "HTTPMANAGER";
    public static int LOGIN_TYPE = 0;
    /**
     * 请求回调
     */
    private RequestCallBack mRequestCallBack;
    /**
     * 正常请求参数集合
     */
    private HashMap<String, String> mParamMap;
    /**
     * 请求路径
     */

    private String mRequestUrl;
    /**
     * 上传文件的集合
     */
    private HashMap<String, File> mFileRequestMap;
    /**
     * 是否是包含文件的请求
     */
    private boolean isFileRequest = false;
    private static final String TOKEN_ERROR_INFO = "Token信息错误";
    private static final String LOGOUT_INFO = "未查询到该token的登录信息";

    /**
     * 循环请求次数
     */
    private int requestCount = 0;

    private String mStrSign;

    /**
     * 测试完删掉这个方法
     * @param requestMapParams
     * @param requestCallBack
     * @param url
     * @return
     */
 /*   protected Callback.Cancelable postRequest(HashMap<String, String> requestMapParams, RequestCallBack requestCallBack, String url,String strSign) {
        mRequestUrl = url;
        mStrSign = strSign;
        mParamMap = requestMapParams;
        isFileRequest = false;
        mRequestCallBack = requestCallBack;
        RequestParams requestParams = new RequestParams(url);
        requestCount++;
//        StringBuffer stringBuffer = new StringBuffer();
        ComPareUtils.ComPareBuilder tokenBuilder = new ComPareUtils.ComPareBuilder();
        requestMapParams.remove("sign");
        requestMapParams.remove("token");
        requestMapParams.put("token", UserLoginInfo.getUserToken());
        for (String key : requestMapParams.keySet()) {
            tokenBuilder.put(key, requestMapParams.get(key));
            requestParams.addBodyParameter(key, requestMapParams.get(key));
        }
        String signStr = tokenBuilder.create().getSignString();
        requestParams.addBodyParameter("sign", mStrSign);
        //requestMapParams.put("version","and." + AppUtils.getAppVersionName());
        requestParams.setConnectTimeout(50 * 1000);
        requestParams.setMethod(HttpMethod.POST);
        requestParams.setCacheMaxAge(0);
        return x.http().post(requestParams, commonCallBack);
    }*/

    protected Callback.Cancelable postRequest(HashMap<String, String> requestMapParams, RequestCallBack requestCallBack, String url) {
        return postRequest(requestMapParams,requestCallBack,url,0);
    }
    /**正式的
     * */
    protected Callback.Cancelable postRequest(HashMap<String, String> requestMapParams, RequestCallBack requestCallBack, String url,int timeOut) {
        timeOut = timeOut * 1000;
        mRequestUrl = url;
        mParamMap = requestMapParams;
        isFileRequest = false;
        mRequestCallBack = requestCallBack;
        RequestParams requestParams = new RequestParams(url);
        requestCount++;
//        StringBuffer stringBuffer = new StringBuffer();
        ComPareUtils.ComPareBuilder tokenBuilder = new ComPareUtils.ComPareBuilder();
        requestMapParams.remove("sign");
        requestMapParams.remove("token");
        requestMapParams.put("token", UserLoginInfo.getUserLoginInfoInstance().getUserToken());
        for (String key : requestMapParams.keySet()) {
            tokenBuilder.put(key, requestMapParams.get(key));
            requestParams.addBodyParameter(key, requestMapParams.get(key));
        }
        String signStr = tokenBuilder.create().getSignString();
        requestParams.addBodyParameter("sign", signStr);
      
        if(timeOut > 30 * 1000){
            requestParams.setConnectTimeout(timeOut);
        }else {
            requestParams.setConnectTimeout(30 * 1000);
        }
        requestParams.addBodyParameter("time", "" + MyLoginUtils.getCuurrentTime());
        requestParams.setMethod(HttpMethod.POST);
        requestParams.setCacheMaxAge(0);
        List<KeyValue> params =  requestParams.getBodyParams();
        StringBuffer stringBuffer = new StringBuffer();
        for(KeyValue keyValue : params){
            if(keyValue.key.equals("token")){continue;}
            stringBuffer.append(keyValue.key + " = " + keyValue.value + "\n");
        }
        stringBuffer.append("url = " + requestParams.getUri());
        Log.i(TAG, "postRequest: " +stringBuffer.toString());
        return x.http().post(requestParams, commonCallBack);
    }

    /**
     * 多文件带参上传
     * @param requestMapParams
     * @param requestFileParams
     * @param requestCallBack
     * @param url
     * @return
     */
    protected Callback.Cancelable postFileRequest(HashMap<String, String> requestMapParams, HashMap<String, File> requestFileParams, RequestCallBack requestCallBack, String url) {
        isFileRequest = true;
        mRequestUrl = url;
        mParamMap = requestMapParams;
        mFileRequestMap = requestFileParams;
        RequestParams requestParams = new RequestParams(url);
        mRequestCallBack = requestCallBack;
        for (String paramsKey : requestMapParams.keySet()) {
            requestParams.addBodyParameter(paramsKey, requestMapParams.get(paramsKey));
        }
        for (String fileKey : requestFileParams.keySet()) {
            requestParams.addBodyParameter(fileKey, requestFileParams.get(fileKey));
        }

        requestCount++;
        if (requestCount > 3) {
            EventBus.getDefault().post(new FroceLogOutMessage());
            return null;
        }

        requestParams.addBodyParameter("token", UserLoginInfo.getUserLoginInfoInstance().getUserToken());
//        requestParams.addBodyParameter("token", "rqp6rICnetyvpqewfX6moJaQsZ3F0GypkHWCmX7OyGqqz7Cel6py17y5mqJ_n3yvgYykYbDRgaSDnKSXjpa6rLrQgmeNt4qau7ansX5ojLB_oqSou96bo4N1gtZ-0d2dxJmLm5eqpdm8ta9veaB4aH-MyqiwuJ5pg5yKzJu1onI");
        requestParams.setMethod(HttpMethod.POST);
        requestParams.setCacheMaxAge(0);
        //萨比尔江 2018-04-26 设置了超时时间和文件上传的属性
        requestParams.setReadTimeout(60000);
        requestParams.setConnectTimeout(30 * 1000);
        requestParams.setMultipart(true);
//        LogUtils.i(TAG + "post请求数据: " + requestParams.toString());
        return x.http().post(requestParams, commonCallBack);

    }

    private Callback.CommonCallback commonCallBack = new Callback.CommonCallback<String>() {
        @Override
        public void onSuccess(final String result) {
            //如果是退出登录请求,不在刷新token
            if (LOGIN_TYPE == 1) {
                LOGIN_TYPE = 0;
                return;
            }

//            LogUtils.i("响应数据:" + result + "\n" + mRequestUrl);
            try {
                if (TextUtils.isEmpty(result)) {
                    if(mRequestCallBack != null){
                        mRequestCallBack.onSuccess(result);
                    }
                    return;
                }
                JSONObject resultJsonObject = new JSONObject(result);
                String resultStatus = resultJsonObject.optString(RefreshToken.QUERY_TOKEN_SUCCESS_CODE_KEY);
                if (RefreshToken.TOKEN_ERROR_LOGIN_CODE_KEY.equals(resultStatus)) {
                    EventBus.getDefault().post(new FroceLogOutMessage());
                    return;
                } else if (RefreshToken.TOKEN_ERROR_REFRESH_CODE_KEY.equals(resultStatus)) {
                    ThreadPoolManager.getInstance().execute(new Runnable() {
                        @Override
                        public void run() {
//                            Looper.prepare();
                            boolean refreshResult = RefreshToken.getInstance().postRequestGetToken();
                            if (refreshResult) {
                                if (isFileRequest) {
                                    postFileRequest(mParamMap, mFileRequestMap, mRequestCallBack, mRequestUrl);
                                } else {
                                    postRequest(mParamMap, mRequestCallBack, mRequestUrl);
                                }
                            } else {
                                UserLoginInfo.getUserLoginInfoInstance().updateUserToken("");
                                PreferenceTools.clear();
                                Stack<SoftReference<Activity>> stack = MyActivityManager.mActivites;
                                if(stack != null && stack.size() > 0){
                                    Activity activity = stack.lastElement().get();
                                    if(activity != null){
                                        Intent intent = new Intent(activity, DengLuActivity.class);
                                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                                                | Intent.FLAG_ACTIVITY_NEW_TASK);
                                        activity.startActivity(intent);
                                    }
                                }
                            }
                        }
                    });
                    return;
                } else {
                    if(mRequestCallBack != null){
                        mRequestCallBack.onSuccess(result);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.i("HttpManager", "父onSuccess: " + e.getMessage());
                if(mRequestCallBack != null){
                    mRequestCallBack.onError(e, true);
                }
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            ex.printStackTrace();
            Log.i("HttpManager", "父error: " + ex.getMessage());
            if(mRequestCallBack != null){
                mRequestCallBack.onError(ex, isOnCallback);
            }
        }

        @Override
        public void onCancelled(CancelledException cex) {
            if(mRequestCallBack != null){
                mRequestCallBack.onCancelled(cex);
            }
        }

        @Override
        public void onFinished() {
            if(mRequestCallBack != null){
                mRequestCallBack.onFinished();
            }
        }
    };

    protected Callback.Cancelable postRequestNonSign(HashMap<String, String> requestMapParams, RequestCallBack requestCallBack, String url){
        mRequestUrl = url;
        mParamMap = requestMapParams;
        isFileRequest = false;
        mRequestCallBack = requestCallBack;
        RequestParams requestParams = new RequestParams(url);
        requestCount++;
//        StringBuffer stringBuffer = new StringBuffer();
        ComPareUtils.ComPareBuilder tokenBuilder = new ComPareUtils.ComPareBuilder();
        requestMapParams.remove("sign");
        requestMapParams.remove("token");
        requestMapParams.put("token", UserLoginInfo.getUserLoginInfoInstance().getUserToken());
        for (String key : requestMapParams.keySet()) {
            tokenBuilder.put(key, requestMapParams.get(key));
            requestParams.addBodyParameter(key, requestMapParams.get(key));
        }
        requestParams.setConnectTimeout(30 * 1000);
        requestParams.setMethod(HttpMethod.POST);
        requestParams.setCacheMaxAge(0);
        return x.http().post(requestParams, commonCallBack);
    }

    public String getRequest(String url ,Map<String,String> params) throws Throwable {
        RequestParams requestParams ;
        if(params != null && params.size() > 0){
            StringBuilder stringBuilder = new StringBuilder();
            Set<String> keySet = params.keySet();
            for(String key : keySet){
                stringBuilder.append("&" + key + "=" + mParamMap.get(key));
            }
            String sign = new ComPareUtils.ComPareBuilder().putMap(params).create().getSignString();
            requestParams = new RequestParams(Host.HTTP_HOME + url + "?" + "sign=" + sign + stringBuilder.toString());
        }else {
            requestParams = new RequestParams(Host.HTTP_HOME + url );
        }
        List<KeyValue> keyValues = requestParams.getBodyParams();
        if(keyValues != null){
            StringBuilder stringBuilder = new StringBuilder();
            for(KeyValue keyValue : keyValues){
                stringBuilder.append(keyValue.key + " = " + keyValue.value + "\n");
            }
            stringBuilder.append("url = " + requestParams.getUri());
            Log.i(TAG, "getRequest: " + stringBuilder.toString());
        }
        return x.http().getSync(requestParams,String.class);
    }
}
